﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Treasure.Model;

namespace Treasure
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        int  tvitemselect= -1;
        PropertyNodeItem TreeItem = null;
        bool rtxChanged = false;
        List<book> books = new List<book>();

        string NameValue ="";
        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            initbooks();
            loadTree();
        }


        private void initbooks()
        {
            using (T_Model mode = new T_Model())
            {
                books = mode.Books.ToList();
            }

        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            loadTree();
        }
        /// <summary>
        /// 节点类
        /// </summary>
        internal class PropertyNodeItem
        {
            public string Icon { get; set; }
            public string EditIcon { get; set; }
            public string DisplayName { get; set; }
            public string Name { get; set; }
            public int id { get; set; }
            public int parentId { get; set; }
            public bool IsExpanded { get; set; }
            public bool IsSelected { get; set; }
            public List<PropertyNodeItem> Children { get; set; }
            public PropertyNodeItem()
            {
                Children = new List<PropertyNodeItem>();
            }
        }
        private void loadTree()
        {
            //tvProperties.Items.Clear();//加载根节点前先清除Treeview控件项
            List<PropertyNodeItem> itemList = new List<PropertyNodeItem>();

            PropertyNodeItem node = new PropertyNodeItem()
            {
                DisplayName = "开发宝典",
                Name = "开发宝典",
                id = 0,
                parentId = 0,
                IsExpanded = true

            };
                         
            //int pid = Convert.ToInt32(dv[0]["ParentId"].ToString());
            ForeachPropertyNode(node, 0);
            itemList.Add(node);

            tvProperties.ItemsSource = null;
            tvProperties.ItemsSource = itemList;
        }
        //无限接循环子节点添加到根节点下面
        private void ForeachPropertyNode(PropertyNodeItem node, int pid)
        {

            if (books.Count > 0)
            {
                foreach (var b in books.Where(b => b.b_parent_id == pid))
                {
                    PropertyNodeItem childNodeItem = new PropertyNodeItem()
                    {
                        DisplayName = b.b_name,
                        Name = b.b_name,
                        id = b.b_id,
                        parentId = b.b_parent_id,
                        IsExpanded = true,
                        IsSelected = false
                    };
                    ForeachPropertyNode(childNodeItem, b.b_id);
                    node.Children.Add(childNodeItem);
                }
            }

        }

        private PropertyNodeItem GetPropertyNode(List<PropertyNodeItem> listitem,int pid)
        {

            if (listitem.Count > 0)
            {
                //PropertyNodeItem childNodeItem = new PropertyNodeItem();
                foreach (var b in listitem)
                {
                   if(b.id==pid)
                        return b;
                    PropertyNodeItem propertyNodeItem= GetPropertyNode(b.Children, pid);
                    if (propertyNodeItem != null && propertyNodeItem.id == pid)
                        return propertyNodeItem;
                }
                
            }
            return null;

        }

        private void tvProperties_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            PropertyNodeItem item = this.tvProperties.SelectedItem as PropertyNodeItem;
            if (item == null )
            {
                rTextBox.Document.Blocks.Clear();
                rtxChanged = false;
                return;
            }
            if (rtxChanged && TreeItem!=null)
            {
                using (T_Model mode = new T_Model())
                {

                    book _book = mode.Books.FirstOrDefault(b => b.b_id == TreeItem.id);
                    if (_book != null)
                    {
                        _book.b_content = ToBStr(RTF(rTextBox));
                        books.First(b => b.b_id == TreeItem.id).b_content = _book.b_content;
                        mode.SaveChanges();
                        rtxChanged = false;
                    }
                }

            }
            var book = books.FirstOrDefault(b => b.b_id == item.id);
            if (book == null || book.b_content == null )
            {
                rTextBox.Document.Blocks.Clear();
                rtxChanged = false;
                return;
            }
            try
            {                
                LoadFromRTF(rTextBox, ToStrB(book.b_content));
                rtxChanged = false;
            }
            catch
            { }
            tvitemselect = item.id;
            TreeItem = item;

        }

        #region 数据转换
        /// <summary>
        /// 用utf-8 把string转换成 byte格式的string 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string ToBStr(string str)
        {
            string StrBy = "";
            if (str == "") return StrBy;
            //byte bys = Convert.ToByte(str);
            byte[] byteStr = Encoding.UTF8.GetBytes(str);
            for (int i = 0; i < byteStr.Length; i++)
            {
                StrBy += byteStr[i].ToString() + " ";
            }
            return StrBy;
        }
        /// <summary>
        /// 用utf-8 把byte格式的string转换成  string
        /// </summary>
        /// <param name="strb"></param>
        /// <returns></returns>
        private string ToStrB(string strb)
        {
            string str = "";
            if (strb == "") return str;
            string[] Bstr = strb.Split(' ');
            byte[] byteStr = new byte[Bstr.Length];
            for (int i = 0; i < Bstr.Length; i++)
            {
                if (Bstr[i] != "")
                    byteStr[i] = Convert.ToByte(Bstr[i]);
            }
            str = Encoding.UTF8.GetString(byteStr);
            return str;
        }
        #endregion


        public static string RTF(RichTextBox richTextBox)
        {
            string rtf = string.Empty;
            TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            using (MemoryStream ms = new MemoryStream())
            {
                textRange.Save(ms, DataFormats.Rtf);
                ms.Seek(0, SeekOrigin.Begin);
                StreamReader sr = new StreamReader(ms);
                rtf = sr.ReadToEnd();
            }

            return rtf;
        }

        public static void LoadFromRTF(RichTextBox richTextBox, string rtf)
        {

            TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms))
                {
                    sw.Write(rtf);
                    sw.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    textRange.Load(ms, DataFormats.Rtf);
                }
            }
        }
        public void namevalue(string _name)
        {
            NameValue = _name;

        }
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            win_NewEdit _NewEdit = new win_NewEdit();
            _NewEdit.nameValue += namevalue;
            _NewEdit.ShowDialog();
            if (_NewEdit.DialogResult == true)
            {
               
                PropertyNodeItem item = TreeItem ;
                int node_id = books.Max(b => b.b_id)+1;
                PropertyNodeItem node = new PropertyNodeItem()
                {                    
                    DisplayName = NameValue,
                    Name = NameValue,
                    id = node_id,
                    parentId = item.id,
                    IsExpanded = true,
                    IsSelected = false
                };
                item.Children.Add(node);                              

                using (T_Model mode = new T_Model())
                {
                    book _book = new book();
                    _book.b_id = node_id;
                    _book.b_name = NameValue;
                    _book.b_parent_id = item.id;
                    mode.Books.Add(_book);
                    books.Add(_book);
                    mode.SaveChanges();
                    loadTree();

                    //books = mode.Books.ToList();
                }
                item.IsExpanded = true;
                item.Children.FirstOrDefault(i=>i.id== node_id).IsSelected=true;
               
            }
            _NewEdit.Close();

        }
        private void Edit_Click(object sender, RoutedEventArgs e)
        {
             win_NewEdit _NewEdit = new win_NewEdit();
            PropertyNodeItem item = this.tvProperties.SelectedItem as PropertyNodeItem;

            if(item==null)
                return;
            _NewEdit.SetName = item.Name;
            _NewEdit.nameValue += namevalue;
            _NewEdit.ShowDialog();
            if (_NewEdit.DialogResult == true)
            {        
                using (T_Model mode = new T_Model())
                {
                    book _book = mode.Books.FirstOrDefault(b => b.b_id == item.id);
                   
                    if (_book != null)
                    {
                        _book.b_name = NameValue;
                        books.First(b => b.b_id == item.id).b_name= NameValue;
                        mode.SaveChanges();
                        loadTree();
                    }
                    //books = mode.Books.ToList();
                }
               
            }
            _NewEdit.Close();
        }
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            PropertyNodeItem item = this.tvProperties.SelectedItem as PropertyNodeItem;

            using (T_Model mode = new T_Model())
            {
                book _book = mode.Books.FirstOrDefault(b => b.b_id == item.id);
                if (_book != null)
                {
                    mode.Books.Remove(_book);
                    mode.SaveChanges();
                   
                
                }
                books.Remove(books.Find(b=>b.b_id==_book.b_id));
                loadTree();
                //books = mode.Books.ToList();
            }

        }
        private void Select_Click(object sender, RoutedEventArgs e)
        {
            win_NewEdit _NewEdit = new win_NewEdit();
          
            //_NewEdit.SetName ="查找";
            _NewEdit.nameValue += namevalue;
            _NewEdit.ShowDialog();
            if (_NewEdit.DialogResult == true)
            {
               var book= books.Find(b => b.b_name.Contains(NameValue));
                PropertyNodeItem node = new PropertyNodeItem()
                {
                    DisplayName = NameValue,
                    Name = NameValue,
                    id = book.b_id,
                    parentId = book.b_parent_id,
                    IsExpanded = true,
                    IsSelected = true
                };
                List<PropertyNodeItem> aa = (List < PropertyNodeItem >)tvProperties.ItemsSource;
                PropertyNodeItem ac = GetPropertyNode(aa, book.b_id);

                TreeViewItem  ab=tvProperties.ItemContainerGenerator.ContainerFromItem(ac) as TreeViewItem;
                //aa.IsExpanded = true;
                //aa.IsSelected = true;
            }
            _NewEdit.Close();
        }
        private void tvProperties_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
          

        }

        private void rTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            rtxChanged = true;
        }
    }
}
